package com.my.library.auth;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.my.library.dao.impl.UserDAO;
import com.my.library.entity.Role;
import com.my.library.entity.User;

@Component
public class CustomInvocationSecurityMetadataSourceService implements InitializingBean {

	private static Map<String, List<String>> requestMap = new LinkedHashMap<String, List<String>>();
	
	@Autowired
	private UserDAO userDAO;
	
	public CustomInvocationSecurityMetadataSourceService() {
		
	}
	
	// 加载所有资源与权限的关系
	public void loadResourceDefine() {
		System.out.println("加载资源与权限的关系");
		requestMap = userDAO.loadRoleAppAuth();
		System.out.println(requestMap);
	}

	// 返回所请求资源所需要的权限
	public List<String> getAttributes(Object object) {
		return requestMap.get(object);
	}
	
	public static void main(String[] args) {
		new CustomInvocationSecurityMetadataSourceService();
	}

	public boolean verify(String requestURL, User u) {
		if(!this.requestMap.containsKey(requestURL)) return true;
		List<String> needRoles = this.requestMap.get(requestURL);
		Set<Role> hasRoles = u.getRoles();
		for(String s: needRoles) {
			for(Role r: hasRoles) {
				if(s.equals(r.getName())) {
					return true;
				}
			}
		}
		return false;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		loadResourceDefine();
	}
}